package org.example.controller;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Folder;
import org.example.entity.Note;
import org.example.service.FolderService;
import org.example.service.NoteService;
import org.example.utils.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 谢娅
 */
@RestController
@Slf4j
@CrossOrigin(origins = "*")
@RequestMapping("/folder")
public class FolderController {

    @Resource
    private FolderService folderService;

    @Resource
    private NoteService noteService;

    private static final Date originDate;

    static {
        try {
            originDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("1970-01-01 00:00:00");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


    @PostMapping("/save")
    public Map<String,Object> save(@RequestBody Folder folder) {
        if(folder.getFolderName() == null || "".equals(folder.getFolderName())){
            return Result.fileMap("文件夹名称不能为空");
        }
        if(folder.getUserId() == null || folder.getUserId() == 0){
            return Result.fileMap("文件夹拥有者id不能为空");
        }
        Folder byId = folderService.getById(folder.getFolderId());
        folder.setUpdatedTime(new Date());
        log.info("folder:{}",folder);
        boolean save;
        if (byId == null){
            save = folderService.save(folder);
        }else{
            save = folderService.updateById(folder);
        }
        if(!save){
            return Result.fileMap("笔记保存失败");
        }
        return Result.successMap("笔记保存成功");
    }

    @GetMapping("/openFolder")
    public Map<String,Object> openFolder(Long userId,Long parentFolderId) {
        Map<String,Object> map = new HashMap<>();
        parentFolderId = parentFolderId == null ? 0 : parentFolderId;
        AtomicInteger fileId = new AtomicInteger(0);
        List<Map> fileList = new ArrayList<>();
        folderService.listByParentFolderId(userId,parentFolderId).forEach(folder -> {
            Map<String,Object> folderMap = new HashMap<>();
            folderMap.put("fileId",fileId.getAndIncrement());
            folderMap.put("folderId",folder.getFolderId());
            folderMap.put("name",folder.getFolderName());
            folderMap.put("type","folder");
            Date createdTime = folder.getCreatedTime() == null ? originDate : folder.getCreatedTime();
            Date updatedTime = folder.getUpdatedTime() == null ? originDate : folder.getUpdatedTime();
            folderMap.put("createdTime",createdTime);
            folderMap.put("updatedTime",updatedTime);
            fileList.add(folderMap);
        });
        noteService.listByParentFolderId(userId,parentFolderId).forEach(note -> {
            Map<String,Object> noteMap = new HashMap<>();
            noteMap.put("fileId",fileId.getAndIncrement());
            noteMap.put("name",note.getTitle());
            noteMap.put("type","note");
            Date createdTime = note.getCreatedTime() == null ? originDate : note.getCreatedTime();
            Date updatedTime = note.getUpdatedTime() == null ? originDate : note.getUpdatedTime();
            noteMap.put("createdTime",createdTime);
            noteMap.put("updatedTime",updatedTime);
            fileList.add(noteMap);
        });
        fileList.sort((o1, o2) -> {
            Map<String,Object> map1 = (Map<String, Object>) o1;
            Map<String,Object> map2 = (Map<String, Object>) o2;
            Date createdTime1 = (Date) map1.get("createdTime");
            Date createdTime2 = (Date) map2.get("createdTime");
            return createdTime2.compareTo(createdTime1);
        });
        map.put("fileList",fileList);
        return Result.successMap(map);
    }

    @DeleteMapping("/remove/{id}")
    public Map<String,Object> remove(@PathVariable Serializable id) {
        Folder folder = folderService.getById(id);
        if (folder == null){
            return Result.fileMap("Folder does not exist");
        }
        return Result.successMap("Folder removed successfully");
    }

    @PutMapping("/update")
    public Map<String,Object> update(@RequestBody Folder folder) {
        if(folder.getFolderId() == null){
            return Result.fileMap("Folder id cannot be empty");
        }
        if(StringUtils.isEmpty(folder.getFolderName())){
            return Result.fileMap("Folder name cannot be empty");
        }
        boolean b = folderService.updateById(folder);
        if(!b){
            return Result.successMap("Folder update failed");
        }
        return Result.successMap("Folder updated successfully");
    }

    @GetMapping("/list")
    public Map<String,Object> list() {
        Map<String,Object> map = new HashMap<>();
        map.put("folderList",new PageInfo<>(folderService.list()));
        return Result.successMap(map);
    }

    @GetMapping("/listByUserId")
    public Map<String,Object> listByUserId(Long userId) {
        Map<String,Object> map = new HashMap<>();
        List<Map> fileList = new ArrayList<>();
        AtomicInteger fileId = new AtomicInteger(0);
        folderService.listByUserId(userId).forEach(folder -> {
            Map<String,Object> folderMap = new HashMap<>();
            folderMap.put("fileId",fileId.getAndIncrement());
            folderMap.put("folderId",folder.getFolderId());
            folderMap.put("name",folder.getFolderName());
            folderMap.put("type","folder");
            folderMap.put("createdTime",folder.getCreatedTime());
            folderMap.put("updatedTime",folder.getUpdatedTime());
            fileList.add(folderMap);
        });
        map.put("fileList",new PageInfo<>(fileList));
        return Result.successMap(map);
    }

    @PostMapping("/search")
    public Map<String,Object> search(@RequestBody Map<String,Object> dataMap) {
        Map<String,Object> map = new HashMap<>();
        if (dataMap == null) {
            return Result.fileMap("参数为空，模糊查询失败");
        }
        String keyword = dataMap.get("keyword") == null ? null : dataMap.get("keyword").toString();
        String startTime = dataMap.get("startTime") == null ? null : dataMap.get("startTime").toString();
        String endTime = dataMap.get("endTime") == null ? null : dataMap.get("endTime").toString();
        Long userId = Long.valueOf(dataMap.get("userId").toString());
        List<Folder> folderList = folderService.search(keyword,startTime,endTime,userId);
        map.put("folderList",folderList);
        return Result.successMap(map);
    }

    @GetMapping("/getInfo/{id}")
    public Map<String,Object> getInfo(@PathVariable Serializable id) {
        return Result.successMap(folderService.getById(id));
    }
}